import requests
import json
from datetime import datetime
from distutils.util import strtobool
from sqlalchemy.orm import Session
from core.response import resp_500
from core.logger import logger
from common.notice_tools import NoticeTools
from common.welab_k8s.k8s_pod import K8sPod
from app.monitor_metrics.models.prom_alarm_record import PromAlarmRecord


class CallbackPodHealHandler():
    """  Self Healing Handler
    """
    def __init__(self):
        self.k8s_pod = K8sPod()
        self.notice_tools = NoticeTools()


    def post_heal_pod_abnormal(self, db: Session, data: dict):
        try:
            logger.info(f"pod abnormal 收到回调告警信息=>{data}")

            # 前期数据判断
            if data["status"] == "resolved":
                logger.info(f"{data['fingerprint']} => pod abnormal was resolved,do nothing")
                return True

            if data["labels"]["namespace"]!= "prod":
                logger.error(f"{data['fingerprint']} => pod abnormal: namespace is not prod")
                return False

            if data["labels"]["token"] != "tG9yadpT4E6P7wfC":
                logger.error(f"{data['fingerprint']} => pod abnormal: token is error")
                return False

            # 处理pod异常的删除操作
            result = self.task_heal_pod_abnormal(db, data)
            if not result:
                logger.error(f"{data['fingerprint']} => handle pod abnormal failed")
                return False

            logger.info(f"{data['fingerprint']} => handle pod abnormal success")
        except Exception as e:
            message = f"pod abnormal callback error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True



    def task_heal_pod_abnormal(self, db: Session, data: dict):
        """
        处理pod异常的删除操作
        """
        # 删除pod
        result = self.k8s_pod.delete_pod_from_namespace(data["labels"]["namespace"], data["labels"]["pod"])
        if not result:
            message = f"故障自愈 => {data['labels']['container']}服务异常.已执行回调操作, 删除pod:{data['labels']['pod']}失败"
            logger.error(f"delete pod failed => {message}")
        else:
            message = f"故障自愈 => {data['labels']['container']}服务异常.已执行回调操作, 删除pod:{data['labels']['pod']}成功"
            logger.info(f"delete pod success => {message}")

        # 发送处理结果信息到企业微信群
        self.notice_tools.send_wechat_group(message)

        # 更新告警记录的comment信息
        update_info = {
            "uuid": data["uuid"],
            "comment": message
        }
        result = PromAlarmRecord.update(db, update_info)
        if not result:
            logger.error(f"update alarm record to database failed")
            return False

        return True


